import {Component} from '@angular/core';
import {GnMessageService, GnTableButton, GnTableComponent} from 'geminis-ng';
import {HttpClient} from "@angular/common/http";
import {TableListComponent} from "./table-list.component";

@Component({
  selector: 'everydata-table-button',
  template: `
    <button nz-button [disabled]="!table?.isSingleSelected" (click)="view()">
      <i nz-icon nzIconfont="download"></i>查看
    </button>
    <button nz-button [disabled]="!table?.isSingleSelected" (click)="export()">
      <i nz-icon nzIconfont="download"></i>导出
    </button>
    <nz-upload [nzShowUploadList]="false" (nzChange)="stateChange($event)"
               [nzAction]="'/api/everydata/tables/import/' + this.tableList.category||''">
      <button nz-button>
        <i nz-icon nzIconfont="upload"></i>导入
      </button>
    </nz-upload>
  `,
  styles: [':host{order: 210;}']
})
@GnTableButton('everydata-table-button')
export class TableButtonComponent {

  table?: GnTableComponent;

  constructor(public tableList: TableListComponent,
              private http: HttpClient,
              private messageService: GnMessageService) {
  }

  view(): void {
    window.open('/center/everydata/list/?tableId=' + this.table?.selectedKey);
  }

  export(): void {
    this.http.get('/api/everydata/tables/' + this.table?.selectedKey, {
      responseType: 'blob'
    }).subscribe(data => {
      const a = document.createElement('a')
      const objectUrl = URL.createObjectURL(data);
      a.href = objectUrl;
      a.download = this.table?.selectedOne.name + '.json';
      a.click();
      URL.revokeObjectURL(objectUrl);
    }, error => {
      this.messageService.warn('导出错误');
    });
  }

  stateChange(state: any): void {
    if (state.type === 'success') {
      this.messageService.success('导入成功');
      this.table?.loadData();
    }
  }

}
